package com.coder4j.auth.service;

import com.coder4j.auth.entity.AuthRoleEntity;
import com.coder4j.enums.AuthRefTypeEnum;
import com.coder4j.auth.mapper.AuthRoleMapper;
import com.coder4j.auth.service.AuthRefService;
import com.coder4j.auth.service.AuthResourceService;
import com.coder4j.auth.vo.AuthRoleVO;
import com.coder4j.auth.service.AuthRoleService;
import com.coder4j.cache.RoleCache;
import com.coder4j.starter.tools.vo.BaseException;
import com.coder4j.starter.web.BaseServiceImpl;
import com.coder4j.starter.web.DataScopeEnums;
import lombok.NonNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * 角色
 * @author keller
 * @date 2024-05-07 17:51:15
 */
@Service
@Slf4j
public class AuthRoleService extends BaseServiceImpl<AuthRoleMapper,AuthRoleEntity,AuthRoleVO>  {

    @Resource
    private AuthRoleMapper mapper;

    @Resource
    @Lazy
    private AuthRefService refService;

    @Resource
    @Lazy
    private AuthResourceService resourceService;


    @Override
    public AuthRoleVO entity2Vo(AuthRoleEntity entity) {
        AuthRoleVO vo = new AuthRoleVO();
        BeanUtils.copyProperties(entity,vo);
        String note = DataScopeEnums.valueOf(entity.getDataScope()).note;
        vo.setDataScopeStr(note);

        return vo;
    }

    @Override
    public AuthRoleEntity vo2Entity(AuthRoleVO vo) {
        AuthRoleEntity entity = new AuthRoleEntity();
        BeanUtils.copyProperties(vo, entity);
        return entity;
    }

    public void setRight(AuthRoleVO vo) {
        Long id = vo.getId();
        AuthRoleEntity role = this.baseGetById(id);
        if(role == null){
            throw BaseException.noData();
        }
        refService.changeOneToMoreRef(AuthRefTypeEnum.RoleRight,id,vo.getRightIds());
    }

    public AuthRoleVO getDetail(@NonNull Long id) {
        AuthRoleVO role = this.baseGetVOById(id);
        if(role == null){
            throw BaseException.noData();
        }

        role.setRightIds(RoleCache.getRights(id));

        return role;
    }
}
